package com.blog.filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class SensitiveWordsFilter implements Filter{
    private List<String> list=new ArrayList<String>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            //1,获取文件真实路径
            ServletContext servletContext = filterConfig.getServletContext();
            String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt");
            //2,读取文件
            BufferedReader br=new BufferedReader(new FileReader(realPath));
            //3,将文件中的每一行数据加载到list中
            String line=null;
            while ((line=br.readLine())!=null){

                System.out.println("敏感字符都有"+line);
                list.add(line);
            }
            //4,关闭流
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//创建request的代理对象,增强getParameter方法
         ServletRequest proxy_req= (ServletRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("getParameter")){
                    String value = (String) method.invoke(request, args);
                    //判断返回结果是否为空
                    if (value!=null){
                        //判断是否有敏感字符
                        for (String  str : list) {
                            if (value.contains(str)){
                                value=value.replaceAll(str,"***");
                            }

                        }
                    }
                    return  value;
                }

                return method.invoke(request,args);
            }
        });

        chain.doFilter(proxy_req,response);
    }

    @Override
    public void destroy() {

    }
}
